//
//  LQPhotoPickerViewController.m
//  LQPhotoPicker
//
//  Created by lawchat on 15/9/22.
//  Copyright (c) 2015年 Fillinse. All rights reserved.
//

#import "LQPhotoPickerController.h"
#import "LQPhotoViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "LQImgPickerActionSheet.h"
#import "JJPhotoManeger.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZLocationManager.h"
@interface LQPhotoPickerController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,LQImgPickerActionSheetDelegate,JJPhotoDelegate,UIActionSheetDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UINavigationControllerDelegate>{
}
@property(nonatomic,assign) BOOL isSelectOriginalPhoto;
@property(nonatomic,assign) CGFloat itemWH;
@property(nonatomic,assign) CGFloat margin;

@property(nonatomic,assign) CGFloat collectionFrameY;
//图片选择器
@property(nonatomic,strong) UIViewController *showActionSheetViewController;
@property (strong, nonatomic) CLLocation *location;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@property (nonatomic, strong)NSMutableArray *imageFileArry;

@end

@implementation LQPhotoPickerController

static NSString * const reuseIdentifier = @"LQPhotoViewCell";
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // 改变相册选择页的导航栏外观
        // _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        //  _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        if (!_showActionSheetViewController) {
            _showActionSheetViewController = self;
            self.marginY = 20;
            self.imageHeight = ([UIScreen mainScreen].bounds.size.width/4.0);
            self.imageWidth = self.imageHeight;
        }
    }
    return self;
}
- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)LQPhotoPicker_initPickerView{
    _showActionSheetViewController = self;
    UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
    self.pickerCollectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
    
    if (_LQPhotoPicker_superView) {
        [_LQPhotoPicker_superView addSubview:self.pickerCollectionView];
    }
    else{
        [self.view addSubview:self.pickerCollectionView];
    }
    
    
    self.pickerCollectionView.delegate=self;
    self.pickerCollectionView.dataSource=self;
    self.pickerCollectionView.backgroundColor = [UIColor whiteColor];
    
    if(_LQPhotoPicker_smallImageArray.count == 0){
        _LQPhotoPicker_smallImageArray = [NSMutableArray array];
    }
    if(_LQPhotoPicker_bigImageArray.count == 0){
        _LQPhotoPicker_bigImageArray = [NSMutableArray array];
    }
    //    self.pushImgName = @"plus.png";
    
    _pickerCollectionView.scrollEnabled = NO;
    
    if (_LQPhotoPicker_imgMaxCount <= 0) {
        _LQPhotoPicker_imgMaxCount = 10;
    }
    
    //添加图片提示
    self.addImgStrLabel = [UILabel lableWithText:@"" colorString:@"4E4F66" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
    [self.pickerCollectionView addSubview:self.addImgStrLabel];
    
    self.subTitleLabel = [UILabel lableWithText:@"" colorString:@"C6C4CF" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:1];
    [self.pickerCollectionView addSubview:self.subTitleLabel];
    __weak typeof(self) weakSelf = self;
    [self.addImgStrLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.pickerCollectionView).offset(viewPix(90));
        make.bottom.equalTo(weakSelf.pickerCollectionView.mas_centerY).offset(-viewPix(5));
    }];
    
    [self.subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.addImgStrLabel);
        make.top.equalTo(weakSelf.addImgStrLabel.mas_bottom).offset(viewPix(10));
    }];
}


-(void)setPushImgName:(NSString *)pushImgName{
    _pushImgName = pushImgName;
}

-(void)setMarginY:(CGFloat)marginY{
    _marginY = marginY;
}

-(void)setImageWidth:(CGFloat)imageWidth{
    _imageWidth = imageWidth;
}

-(void)setImageHeight:(CGFloat)imageHeight{
    _imageHeight = imageHeight;
}

-(void)setLQPhotoPicker_imgMaxCount:(NSInteger)LQPhotoPicker_imgMaxCount{
    _LQPhotoPicker_imgMaxCount = LQPhotoPicker_imgMaxCount;
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imageURLArry.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UINib *nib = [UINib nibWithNibName:@"LQPhotoViewCell" bundle: [NSBundle mainBundle]];
    [collectionView registerNib:nib forCellWithReuseIdentifier:@"LQPhotoViewCell"];
    LQPhotoViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"LQPhotoViewCell" forIndexPath:indexPath];
    [cell.profilePhoto setContentMode:UIViewContentModeScaleAspectFill];
    cell.profilePhoto.clipsToBounds = YES;
    if (indexPath.row == _imageURLArry.count) {
        [cell.profilePhoto setImage:[UIImage imageNamed:_pushImgName]];
        cell.closeButton.hidden = YES;
        //没有任何图片
        if (_imageURLArry.count == 0) {
            _addImgStrLabel.hidden = NO;
            _subTitleLabel.hidden = NO;
        }else{
            _addImgStrLabel.hidden = YES;
            _subTitleLabel.hidden = YES;
        }
    }else{
        NSDictionary *dic = _imageURLArry[indexPath.item];
        NSString *urlStr = [NSString stringWithFormat:@"%@",dic.allValues[0]];
        
        [cell.profilePhoto sd_setImageWithURL:[NSURL URLWithString:urlStr]];
        cell.closeButton.hidden = NO;
    }
    [cell setBigImgViewWithImage:nil];
    cell.profilePhoto.tag = [indexPath item];
    //添加图片cell点击事件
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
    singleTap.numberOfTapsRequired = 1;
    cell.profilePhoto .userInteractionEnabled = YES;
    [cell.profilePhoto  addGestureRecognizer:singleTap];
    cell.closeButton.tag = [indexPath item];
    [cell.closeButton addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
    [self changeCollectionViewHeight];
    return cell;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.imageWidth>0) {
        return CGSizeMake(self.imageWidth, self.imageHeight);
    }
    return CGSizeMake(([UIScreen mainScreen].bounds.size.width-64) /4 ,([UIScreen mainScreen].bounds.size.width-64) /4);
}

//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(self.marginY, 15, self.marginY, 15);
}

//点击cell
- (void)tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
    __weak typeof(self) weakSelf = self;
    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    NSInteger index = tableGridImage.tag;
    if (index == (_LQPhotoPicker_smallImageArray.count)) {
        //添加新图片
        [self.view endEditing:YES];
        [self addNewImg];
    }else{
        //查看大图
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_LQPhotoPicker_selectedAssetArray selectedPhotos:_LQPhotoPicker_smallImageArray index:index];
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            weakSelf.LQPhotoPicker_smallImageArray = [NSMutableArray arrayWithArray:photos];
            weakSelf.LQPhotoPicker_selectedAssetArray = [NSMutableArray arrayWithArray:assets];
            weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
            [weakSelf.pickerCollectionView reloadData];
            weakSelf.pickerCollectionView.contentSize = CGSizeMake(0, ((weakSelf.LQPhotoPicker_smallImageArray.count + 2) / 3 ) * (weakSelf.margin + weakSelf.itemWH));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

#pragma mark - 选择图片
- (void)addNewImg{
    if (_LQPhotoPicker_smallImageArray.count == _LQPhotoPicker_imgMaxCount) {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"选择图片数量已达上限" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [alert show];
        return;
    }
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"去相册选择", nil];
    [sheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // take photo / 去拍照
        [self takePhoto];
    } else if (buttonIndex == 1) {
        [self pushTZImagePickerController];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { // 去设置界面，开启相机访问权限
        if (iOS8Later) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}
#pragma mark - UIImagePickerController
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(CLLocation *location, CLLocation *oldLocation) {
        weakSelf.location = location;
    } failureBlock:^(NSError *error) {
        weakSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

#pragma mark - TZImagePickerController
//去相册
- (void)pushTZImagePickerController{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.LQPhotoPicker_imgMaxCount columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    //    imagePickerVc.navigationBar.translucent = NO;
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    // 1.设置目前已经选中的图片数组
    imagePickerVc.selectedAssets = _LQPhotoPicker_selectedAssetArray;
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.isStatusBarDefault = YES;
#pragma mark - 到这里为止
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    }];

    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
//        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:self.location completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                    
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        [[TZImageManager manager] getOriginalPhotoWithAsset:assetModel.asset completion:^(UIImage *photo, NSDictionary *info) {
                            [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image info:info];
                        }];
                        
                        
                    }];
                }];
            }
        }];
    }
}

- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image info:(NSDictionary *)info {
    [self uploadImageWithImageArry:@[image] infos:@[info] photos:@[] assets:@[asset]];
//    [self uploadImageWithPhotos:@[image] filePaths:@[info]];
//    [self.imageFileArry addObject:[NSString stringWithFormat:@"%@",info[@"PHImageFileURLKey"]]];
//    [_LQPhotoPicker_selectedAssetArray addObject:asset];
//    [_LQPhotoPicker_smallImageArray addObject:image];
//    [_pickerCollectionView reloadData];
    NSLog(@">>>???>>>选择完成2");
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        NSLog(@"location:%@",phAsset.location);
    }
}

-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    NSMutableArray *fileArry = [NSMutableArray arrayWithArray:self.imageFileArry];
//    NSMutableArray *urlArry = [NSMutableArray arrayWithArray:self.imageURLArry];
    NSMutableArray *infoDicArry = [NSMutableArray arrayWithArray:infos];
    NSMutableArray *photosArry = [NSMutableArray arrayWithArray:photos];
    for (NSInteger i=0; i<infos.count; i++) {
        NSDictionary *dic = infos[i];
        NSString *filePath = [NSString stringWithFormat:@"%@",dic[@"PHImageFileURLKey"]];
        if ([fileArry containsObject:filePath]) {
            UIImage *image = photos[i];
            [photosArry removeObject:image];
            [infoDicArry removeObject:dic];
            [fileArry removeObject:filePath];
        }else{
            [self.imageFileArry addObject:filePath];
        }
    }
    
    if (photosArry.count>0) {
        [self uploadImageWithImageArry:photosArry infos:infoDicArry photos:photos assets:assets];
//        [self uploadImageWithPhotos:photosArry filePaths:infoDicArry];
    }
    
  
    
    for (NSInteger i=0; i<fileArry.count; i++) {
        NSString *filePath = fileArry[i];
        for (NSInteger j=0; j<self.imageURLArry.count; j++) {
            NSDictionary *dic = self.imageURLArry[j];
//            NSArray *allKeys = dic.allKeys;
            NSString *key = [NSString stringWithFormat:@"%@",dic.allKeys[0]];
            if ([key isEqualToString:filePath]) {
                [self deletImageWithUrl:dic[filePath] dic:dic needRemove:NO];
            }
        }
    }
    
    
    
//    _LQPhotoPicker_smallImageArray = [NSMutableArray arrayWithArray:photos];
//    _LQPhotoPicker_selectedAssetArray = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
//    [_pickerCollectionView reloadData];

    
    // 1.打印图片名字
    //    [self printAssetsName:assets];
    // 2.图片位置信息
    if (iOS8Later) {
        for (PHAsset *phAsset in assets) {
            NSLog(@"location:%@",phAsset.location);
        }
    }
}


-(void)deletImageWithUrl:(NSString *)url dic:(NSDictionary *)dic needRemove:(BOOL)remove{
//    [RequestUtil withPOST:@"Revisit/cancelFile" parameters:@{defaultParm,@"file":url} success:^(NSString *status, NSString *message, id responseData) {
//        if ([status isEqualToString:@"200"]) {
//            NSInteger index = [self.imageURLArry indexOfObject:dic];
//            [self.imageURLArry removeObject:dic];
//            [self.imageFileArry removeObject:[NSString stringWithFormat:@"%@",dic.allKeys[0]]];
//            if (remove == YES) {
//                [self.LQPhotoPicker_smallImageArray removeObjectAtIndex:index];
//                [self.LQPhotoPicker_selectedAssetArray removeObjectAtIndex:index];
//            }
//            [self.pickerCollectionView reloadData];
//        }
//    } failure:^(NSError *error) {
//        
//    }];
}

-(void)uploadImageWithImageArry:(NSArray *)imageArry infos:(NSArray *)infos photos:(NSArray *)photos  assets:(NSArray *)assets{
//    [RequestUtil uploadImage:@"Revisit/uploadImageFile" params:@{defaultParm} indexName:@"pic[]" imagePathList:imageArry success:^(id responseObject) {
//        if ([responseObject[@"code"] isEqualToString:@"200"]) {
//            NSArray *tempArry = responseObject[@"data"];
//            for (NSInteger i=0; i<tempArry.count; i++) {
//                NSString *filePath = [NSString stringWithFormat:@"%@",infos[i][@"PHImageFileURLKey"]];
//                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//                [dic setValue:tempArry[i] forKey:filePath];
//                [self.imageURLArry addObject:dic];
//                [self.imageFileArry addObject:filePath];
//            }
//            if (photos.count>0) {
//                self.LQPhotoPicker_smallImageArray = [NSMutableArray arrayWithArray:photos];
//                self.LQPhotoPicker_selectedAssetArray = [NSMutableArray arrayWithArray:assets];
//            }else{
//                [self.LQPhotoPicker_selectedAssetArray addObject:assets[0]];
//                [self.LQPhotoPicker_smallImageArray addObject:imageArry[0]];
//            }
//            [self.pickerCollectionView reloadData];
//        }
//    } failure:^(NSError *error) {
//        [TooltipView showMessage:@"图片上传失败，请重试" offset:0];
//    }];
}


-(BOOL)isAlbumCanSelect:(NSString *)albumName result:(id)result {
    /*
     if ([albumName isEqualToString:@"个人收藏"]) {
     return NO;
     }
     if ([albumName isEqualToString:@"视频"]) {
     return NO;
     }*/
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanSelect:(id)asset {
    /*
     if (iOS8Later) {
     PHAsset *phAsset = asset;
     switch (phAsset.mediaType) {
     case PHAssetMediaTypeVideo: {
     // 视频时长
     // NSTimeInterval duration = phAsset.duration;
     return NO;
     } break;
     case PHAssetMediaTypeImage: {
     // 图片尺寸
     if (phAsset.pixelWidth > 3000 || phAsset.pixelHeight > 3000) {
     // return NO;
     }
     return YES;
     } break;
     case PHAssetMediaTypeAudio:
     return NO;
     break;
     case PHAssetMediaTypeUnknown:
     return NO;
     break;
     default: break;
     }
     } else {
     ALAsset *alAsset = asset;
     NSString *alAssetType = [[alAsset valueForProperty:ALAssetPropertyType] stringValue];
     if ([alAssetType isEqualToString:ALAssetTypeVideo]) {
     // 视频时长
     // NSTimeInterval duration = [[alAsset valueForProperty:ALAssetPropertyDuration] doubleValue];
     return NO;
     } else if ([alAssetType isEqualToString:ALAssetTypePhoto]) {
     // 图片尺寸
     CGSize imageSize = alAsset.defaultRepresentation.dimensions;
     if (imageSize.width > 3000) {
     // return NO;
     }
     return YES;
     } else if ([alAssetType isEqualToString:ALAssetTypeUnknown]) {
     return NO;
     }
     }*/
    return YES;
}
#pragma mark - 删除照片
- (void)deletePhoto:(UIButton *)sender{
    NSDictionary *dic = self.imageURLArry[sender.tag];
//    [_LQPhotoPicker_smallImageArray removeObjectAtIndex:sender.tag];
//    [_LQPhotoPicker_selectedAssetArray removeObjectAtIndex:sender.tag];
    [self deletImageWithUrl:[NSString stringWithFormat:@"%@",dic.allValues[0]] dic:dic needRemove:YES];
//    [self.pickerCollectionView reloadData];
    
//    [self.pickerCollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:sender.tag inSection:0]]];
//
//    for (NSInteger item = sender.tag; item <= _LQPhotoPicker_smallImageArray.count; item++) {
//        LQPhotoViewCell *cell = (LQPhotoViewCell*)[self.pickerCollectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
//        cell.closeButton.tag--;
//        cell.profilePhoto.tag--;
//    }
//    //没有任何图片
//    if (_LQPhotoPicker_smallImageArray.count == 0) {
//        _addImgStrLabel.hidden = NO;
//    }
//    else{
//        _addImgStrLabel.hidden = YES;
//    }
    [self changeCollectionViewHeight];
}

#pragma mark - LQImgPickerActionSheetDelegate (返回选择的图片：缩略图，压缩原长宽比例大图)
//- (void)getSelectImgWithALAssetArray:(NSArray*)ALAssetArray thumbnailImgImageArray:(NSArray*)thumbnailImgArray{
//
//    //（ALAsset）类型 Array
//    _LQPhotoPicker_selectedAssetArray = [NSMutableArray arrayWithArray:ALAssetArray];
//    //正方形缩略图 Array
//    _LQPhotoPicker_smallImageArray = [NSMutableArray arrayWithArray:thumbnailImgArray] ;
//
//    [self.pickerCollectionView reloadData];
//}

#pragma mark - 改变view，collectionView高度
- (void)changeCollectionViewHeight{
    NSInteger count = 1;
    if (_LQPhotoPicker_selectedAssetArray.count>0) {
        CGFloat num = _LQPhotoPicker_selectedAssetArray.count%4;
        count = _LQPhotoPicker_selectedAssetArray.count/4;
        if (num>0 || (num == 0 &&_LQPhotoPicker_selectedAssetArray.count<_LQPhotoPicker_imgMaxCount)) {
            count = count+1;
        }
    }
    
    if (_collectionFrameY) {
        _pickerCollectionView.frame = CGRectMake(0, _collectionFrameY, [UIScreen mainScreen].bounds.size.width, ((float)self.imageHeight +self.marginY)*count+self.marginY);
    }
    else{
        _pickerCollectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, ((float)self.imageHeight +self.marginY)*count+self.marginY);
    }
    if (_LQPhotoPicker_delegate && [_LQPhotoPicker_delegate respondsToSelector:@selector(LQPhotoPicker_pickerViewFrameChanged)]) {
        [_LQPhotoPicker_delegate LQPhotoPicker_pickerViewFrameChanged];
    }
}

- (void)LQPhotoPicker_updatePickerViewFrameY:(CGFloat)Y{
    _collectionFrameY = Y;
    NSInteger count = 1;
    if (_LQPhotoPicker_selectedAssetArray.count>0) {
        CGFloat num = _LQPhotoPicker_selectedAssetArray.count%4;
        count = _LQPhotoPicker_selectedAssetArray.count/4;
        if (num>0|| (num == 0 && _LQPhotoPicker_selectedAssetArray.count<_LQPhotoPicker_imgMaxCount)) {
            count = count+1;
        }
    }
    
    _pickerCollectionView.frame = CGRectMake(0, Y, [UIScreen mainScreen].bounds.size.width, ((float)self.imageHeight +self.marginY)* count+self.marginY);
}

#pragma mark - 防止奔溃处理
-(void)photoViwerWilldealloc:(NSInteger)selecedImageViewIndex{
    NSLog(@"最后一张观看的图片的index是:%zd",selecedImageViewIndex);
}

- (NSData *)getBigIamgeDataWithALAsset:(ALAsset*)set{
    UIImage *img = [UIImage imageWithCGImage:set.defaultRepresentation.fullResolutionImage
                                       scale:set.defaultRepresentation.scale
                                 orientation:(UIImageOrientation)set.defaultRepresentation.orientation];
    
    return UIImageJPEGRepresentation(img, 0.5);
}
- (UIImage *)getBigIamgeWithALAsset:(ALAsset*)set{
    //压缩 -- 需传入方向和缩放比例，否则方向和尺寸都不对
    NSData *imageData = [self getBigIamgeDataWithALAsset:set];
    [_LQPhotoPicker_bigImgDataArray addObject:imageData];
    return [UIImage imageWithData:imageData];
}

- (UIImage *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
}  



#pragma mark - 获得选中图片各个尺寸
- (NSMutableArray*)LQPhotoPicker_getALAssetArray{
    return _LQPhotoPicker_selectedAssetArray;
}

- (NSMutableArray*)LQPhotoPicker_getBigImageArray{
    _LQPhotoPicker_bigImageArray = [NSMutableArray array];
    _LQPhotoPicker_bigImgDataArray = [NSMutableArray array];
    //        for (PHAsset *set in _LQPhotoPicker_selectedAssetArray) {
    //                [_LQPhotoPicker_bigImageArray addObject:[self getBigIamgeWithALAsset:set]];
    //
    //            }
    
    for (UIImage *ima in _LQPhotoPicker_smallImageArray) {
        [_LQPhotoPicker_bigImageArray addObject:ima];
    }
    return _LQPhotoPicker_bigImageArray;
}

- (NSMutableArray*)LQPhotoPicker_getBigImageDataArray{
    _LQPhotoPicker_bigImageArray = [NSMutableArray array];
        _LQPhotoPicker_bigImgDataArray = [NSMutableArray array];
        for (ALAsset *set in _LQPhotoPicker_selectedAssetArray) {
            [_LQPhotoPicker_bigImageArray addObject:[self getBigIamgeWithALAsset:set]];
        }

    return _LQPhotoPicker_bigImgDataArray;
}

- (NSMutableArray*)LQPhotoPicker_getSmallImageArray{
    return nil;
}

- (NSMutableArray*)LQPhotoPicker_getSmallDataImageArray{
    _LQPhotoPicker_smallDataImageArray = [NSMutableArray array];
        for (UIImage *smallImg in _LQPhotoPicker_smallImageArray) {
            NSData *smallImgData = UIImagePNGRepresentation(smallImg);
            [_LQPhotoPicker_smallDataImageArray addObject:smallImgData];
        }
    return _LQPhotoPicker_smallDataImageArray;
}
- (CGRect)LQPhotoPicker_getPickerViewFrame{
    return self.pickerCollectionView.frame;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


#pragma mark---懒加载
-(NSMutableArray *)imageFileArry{
    if (!_imageFileArry) {
        _imageFileArry = [NSMutableArray array];
    }
    return _imageFileArry;
}
-(NSMutableArray *)imageURLArry{
    if (!_imageURLArry) {
        _imageURLArry = [NSMutableArray array];
    }
    return _imageURLArry;
}

-(NSMutableArray *)LQPhotoPicker_selectedAssetArray{
    if (!_LQPhotoPicker_selectedAssetArray) {
        _LQPhotoPicker_selectedAssetArray = [NSMutableArray array];
    }
    return _LQPhotoPicker_selectedAssetArray;
}

@end

